package com.jhgsys.internal.accident.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.accident.constant.AccidentConstant;
import com.jhgsys.internal.accident.dto.AccidentReportDto;
import com.jhgsys.internal.accident.dto.AccidentReportReasonDto;
import com.jhgsys.internal.accident.dto.AccidentReportRectificationDto;
import com.jhgsys.internal.accident.dto.AccidentReportTimelineDto;
import com.jhgsys.internal.accident.entity.*;
import com.jhgsys.internal.accident.service.*;
import com.jhgsys.internal.base.entity.BaseProject;
import com.jhgsys.internal.base.service.IBaseCautionaryLessonService;
import com.jhgsys.internal.base.service.IBaseProjectService;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.constant.ModuleManagerPermissionConstant;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.BeanHelper;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.dict.service.IDictService;
import com.jhgsys.internal.formDesign.entity.AccidentRectificationAuditRecord;
import com.jhgsys.internal.formDesign.entity.AccidentSurveyAuditRecord;
import com.jhgsys.internal.formDesign.service.IAccidentRectificationAuditRecordService;
import com.jhgsys.internal.formDesign.service.IAccidentSurveyAuditRecordService;
import com.jhgsys.internal.system.entity.Dept;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IDeptService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  Controller
 *
 * @author admin
 * @date 2024-08-07 16:43:01
 */
@Slf4j
@Validated
@Controller
public class AccidentReportController extends BaseController {

    @Autowired
    private IAccidentReportService accidentReportService;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private IAccidentReportInkuryUserService accidentReportInkuryUserService;

    @Autowired
    private IAccidentReportCulpritUserService accidentReportCulpritUserService;

    @Autowired
    private IAccidentReportFileService accidentReportFileService;

    @Autowired
    private IAccidentReportReasonFileService accidentReportReasonFileService;

    @Autowired
    private IAccidentReportReasonService accidentReportReasonService;

    @Autowired
    private IAccidentRectificationAuditRecordService accidentRectificationAuditRecordService;

    @Autowired
    private IAccidentSurveyAuditRecordService accidentSurveyAuditRecordService;

    @Autowired
    private IBaseCautionaryLessonService baseCautionaryLessonService;

    @Autowired
    private IBaseProjectService baseProjectService;

    @Autowired
    private IAccidentReportRectificationService accidentReportRectificationService;

    @Autowired
    private IAccidentReportTimelineService accidentReportTimelineService;

    @Autowired
    private IAccidentReportRectificationFileService accidentReportRectificationFileService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport")
    @RequiresPermissions("accidentReport:view")
    public String accidentReportIndex(Model model){
        setModelAttribute(model);
        return FebsUtil.view("accidentReport/accidentReportList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/detail/{reportId}")
    @RequiresPermissions("accidentReport:view")
    public String accidentReportDetail(Model model, @PathVariable("reportId") String reportId) throws JsonProcessingException {
        setModelAttribute(model);
        AccidentReportDto accidentReportDto = accidentReportService.findAccidentReportById(reportId);
        model.addAttribute("accidentReport", JSON.parse(new ObjectMapper().writeValueAsString(accidentReportDto)));
        return FebsUtil.view("accidentReport/accidentReportDetail");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/detailForLesson/{reportId}/{lessonId}")
    @RequiresPermissions("accidentReport:view")
    public String accidentReportDetailForLesson(Model model, @PathVariable("reportId") String reportId, @PathVariable("lessonId") String lessonId) throws JsonProcessingException {
        setModelAttribute(model);
        AccidentReportDto accidentReportDto = accidentReportService.findAccidentReportById(reportId);
        model.addAttribute("accidentReport", JSON.parse(new ObjectMapper().writeValueAsString(accidentReportDto)));
        model.addAttribute("baseCautionaryLesson", baseCautionaryLessonService.findBaseCautionaryLessonById(lessonId));
        return FebsUtil.view("base/baseCautionaryLesson/accidentReportDetailForLesson");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/accidentReportBaseInfo/{id}")
    @RequiresPermissions("accidentReport:view")
    public String accidentReportBaseInfo(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        AccidentReportDto accidentReportDto = accidentReportService.findAccidentReportById(id);
        model.addAttribute("accidentReport", JSON.parse(new ObjectMapper().writeValueAsString(accidentReportDto)));
        return FebsUtil.view("accidentReport/accidentReportBaseInfo");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReportSurvey")
    @RequiresPermissions("accidentReportSurvey:view")
    public String accidentReportSurveyIndex(Model model){
        setModelAttribute(model);
        return FebsUtil.view("accidentReport/accidentReportSurveyList");
//        return FebsUtil.view("accidentReport/treeTable");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReportSurveyAudit")
    @RequiresPermissions("accidentReportSurveyAudit:view")
    public String accidentReportSurveyAuditIndex(Model model){
        setModelAttribute(model);
        return FebsUtil.view("accidentReport/accidentReportSurveyAuditList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReportRectification")
    @RequiresPermissions("accidentReportRectification:view")
    public String accidentReportRectificationIndex(Model model){
        setModelAttribute(model);
        return FebsUtil.view("accidentReport/accidentReportRectifyList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReportRectificationAudit")
    @RequiresPermissions("accidentReportRectificationAudit:view")
    public String accidentReportRectificationAuditIndex(Model model){
        setModelAttribute(model);
        return FebsUtil.view("accidentReport/accidentReportRectifyAuditList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/add/{tenantId}")
    @RequiresPermissions("accidentReport:add")
    public String accidentReportAdd(Model model, @PathVariable("tenantId") String tenantId){
        AccidentReport accidentReport = new AccidentReport();
        model.addAttribute("accidentReport",accidentReport);
        setModelAttribute(model);
        return FebsUtil.view("accidentReport/accidentReportEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/update/{id}")
    @RequiresPermissions("accidentReport:edit")
    public String accidentReportUpdate(Model model, @PathVariable("id") String id){
        setModelAttribute(model);
        model.addAttribute("accidentReport", accidentReportService.findAccidentReportById(id));
        return FebsUtil.view("accidentReport/accidentReportEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/surveyRecord/{reportId}/{reportRectificationId}")
    @RequiresPermissions("accidentReport:surveyRecord")
    public String reportSurveyRecord(Model model, @PathVariable("reportId") String reportId, @PathVariable("reportRectificationId") String reportRectificationId) throws JsonProcessingException {
        setModelAttribute(model);
        AccidentReportDto accidentReportDto = accidentReportService.findAccidentReportById(reportId);
        //根据id查询事故整改措施
        if(StringUtils.isNotEmpty(reportRectificationId)){
            if(CollectionUtils.isNotEmpty(accidentReportDto.getRectificationOpinionList())) {
                List<AccidentReportRectification> collect = accidentReportDto.getRectificationOpinionList().stream().filter(d -> d.getReportRectificationId().equals(reportRectificationId)).collect(Collectors.toList());
                accidentReportDto.setRectificationOpinionList(collect);
            }
        }else{
            accidentReportDto.setReportReasonList(null);
        }
        //事故调查审核记录
        accidentReportDto.setSurveyAuditRecordList(accidentSurveyAuditRecordService.list(new LambdaQueryWrapper<AccidentSurveyAuditRecord>()
                .eq(AccidentSurveyAuditRecord::getReportId,reportId)
                .orderByDesc(AccidentSurveyAuditRecord::getCreatedTime)
        ));
        //项目
        BaseProject baseProject = new BaseProject();
        baseProject.setTenantId(getCurrentTenantId());
        baseProject.setStatus("1");
        List<BaseProject> projectList = baseProjectService.findBaseProjects(baseProject);
        model.addAttribute("projectList",projectList);
        model.addAttribute("accidentReport", JSON.parse(new ObjectMapper().writeValueAsString(accidentReportDto)));
        return FebsUtil.view("accidentReport/reportSurveyRecord");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/rectifyRecord/{reportId}/{reportRectificationId}")
    @RequiresPermissions("accidentReport:rectifyRecord")
    public String reportRectifyRecord(Model model, @PathVariable("reportId") String reportId, @PathVariable("reportRectificationId") String reportRectificationId) throws JsonProcessingException {
        setModelAttribute(model);
        AccidentReportDto accidentReportDto = accidentReportService.findAccidentReportById(reportId);
        AccidentReportRectification accidentReportRectificationById = accidentReportRectificationService.findAccidentReportRectificationById(reportRectificationId);
//        //事故原因整改附件
//        accidentReportReasonDto.setAccidentReasonRectifyFileList(accidentReportReasonFileService.list(new LambdaQueryWrapper<AccidentReportReasonFile>()
//                .eq(AccidentReportReasonFile::getReportReasonId,reportReasonId)
//                .eq(AccidentReportReasonFile::getReportFileType,"2")
//        ));
//        //事故原因调查附件
//        accidentReportReasonDto.setAccidentReasonSurveyFileList(accidentReportReasonFileService.list(new LambdaQueryWrapper<AccidentReportReasonFile>()
//                .eq(AccidentReportReasonFile::getReportReasonId,reportReasonId)
//                .eq(AccidentReportReasonFile::getReportFileType,"1")
//        ));
//        //事故原因整改审核记录
//        accidentReportReasonDto.setRectifyAuditRecordList(accidentRectificationAuditRecordService.list(new LambdaQueryWrapper<AccidentRectificationAuditRecord>()
//                .eq(AccidentRectificationAuditRecord::getReportReasonId,reportReasonId)
//                .orderByDesc(AccidentRectificationAuditRecord::getCreatedTime)
//        ));
        model.addAttribute("accidentReport", JSON.parse(new ObjectMapper().writeValueAsString(accidentReportDto)));
        model.addAttribute("accidentReportRectification", JSON.parse(new ObjectMapper().writeValueAsString(accidentReportRectificationById)));
        return FebsUtil.view("accidentReport/reportRectifyRecord");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/surveyAudit/{reportId}")
    @RequiresPermissions("accidentReport:surveyAudit")
    public String reportSurveyAudit(Model model, @PathVariable("reportId") String reportId) throws JsonProcessingException {
        setModelAttribute(model);
        AccidentReportDto accidentReportDto = accidentReportService.findAccidentReportById(reportId);
        model.addAttribute("accidentReport", JSON.parse(new ObjectMapper().writeValueAsString(accidentReportDto)));
        return FebsUtil.view("accidentReport/reportSurveyAudit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/rectifyAudit/{reportId}/{reportReasonId}")
    @RequiresPermissions("accidentReport:rectifyAudit")
    public String reportRectifyAudit(Model model, @PathVariable("reportId") String reportId, @PathVariable("reportReasonId") String reportReasonId) throws JsonProcessingException {
        setModelAttribute(model);
        AccidentReportDto accidentReportDto = accidentReportService.findAccidentReportById(reportId);
        AccidentReportReasonDto accidentReportReasonDto = accidentReportReasonService.findAccidentReportReasonById(reportReasonId);
        //事故原因整改附件
        accidentReportReasonDto.setAccidentReasonRectifyFileList(accidentReportReasonFileService.list(new LambdaQueryWrapper<AccidentReportReasonFile>()
                .eq(AccidentReportReasonFile::getReportReasonId,reportReasonId)
                .eq(AccidentReportReasonFile::getReportFileType,"2")
        ));
        //事故原因调查附件
        accidentReportReasonDto.setAccidentReasonSurveyFileList(accidentReportReasonFileService.list(new LambdaQueryWrapper<AccidentReportReasonFile>()
                .eq(AccidentReportReasonFile::getReportReasonId,reportReasonId)
                .eq(AccidentReportReasonFile::getReportFileType,"1")
        ));
        model.addAttribute("accidentReport", JSON.parse(new ObjectMapper().writeValueAsString(accidentReportDto)));
        model.addAttribute("accidentReportReason", JSON.parse(new ObjectMapper().writeValueAsString(accidentReportReasonDto)));
        return FebsUtil.view("accidentReport/reportRectifyAudit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/surveyAssign/{id}")
    @RequiresPermissions("accidentReport:surveyAssign")
    public String accidentReportSurveyAssign(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        AccidentReportDto accidentReportDto = accidentReportService.findAccidentReportById(id);
        model.addAttribute("accidentReport", JSON.parse(new ObjectMapper().writeValueAsString(accidentReportDto)));
        return FebsUtil.view("accidentReport/reportSurveyAssign");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "accidentReport/rectificationAssign/{id}")
    @RequiresPermissions("accidentReport:rectificationAssign")
    public String accidentReportRectificationAssign(Model model, @PathVariable("id") String id){
        model.addAttribute("accidentReport", accidentReportService.findAccidentReportById(id));
        return FebsUtil.view("accidentReport/reportRectificationAssign");
    }

    /**
     * 查询（所有）
     * @author admin
     * @date 2024-08-07 16:43:01
     */
    @GetMapping("accidentReport")
    @ResponseBody
    @RequiresPermissions("accidentReport:view")
    public FebsResponse getAllAccidentReports(AccidentReport accidentReport) {
        return new FebsResponse().success().data(accidentReportService.findAccidentReports(accidentReport));
    }

    /**
     * 查询（分页）
     * @author admin
     * @date 2024-08-07 16:43:01
     */
    @GetMapping("accidentReport/list")
    @ResponseBody
    @RequiresPermissions("accidentReport:view")
    public FebsResponse accidentReportList(QueryRequest request, AccidentReportDto accidentReportDto) {
        //如果不是总公司用户，或者模块管理员，则只查询自己上报的事故信息,或者指派的调查人是自己的事故
        if(!hasHeadCompanyRole() && !hasPermission(ModuleManagerPermissionConstant.ACCIDENT)){
            accidentReportDto.setCreatedBy(getCurrentUser().getUserId());
        }
        if(null == accidentReportDto.getTenantId()){
            accidentReportDto.setTenantId(getCurrentTenantId());
        }
        Map<String, Object> dataTable = getDataTable(this.accidentReportService.findAccidentReports(request, accidentReportDto));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 调查录入 以AccidentReport为主表查询（所有）
     * @author admin
     * @date 2024-08-20 15:49:12
     * @param accidentReportDto accidentReportDto
     * @return List<AccidentReportDto>
     */
    @GetMapping("accidentReport/recordList")
    @ResponseBody
    @RequiresPermissions("accidentReport:view")
    public FebsResponse accidentReportRecordList(AccidentReportDto accidentReportDto) {
        //如果不是总公司用户，或者模块管理员，则只查询自己上报的事故信息,或者指派的调查人是自己的事故
        if(!hasHeadCompanyRole() && !hasPermission(ModuleManagerPermissionConstant.ACCIDENT)){
            accidentReportDto.setCreatedBy(getCurrentUser().getUserId());
        }
        if(null == accidentReportDto.getTenantId()){
            accidentReportDto.setTenantId(getCurrentTenantId());
        }
        return new FebsResponse().success().data(accidentReportService.findAccidentReportsBySql(accidentReportDto));
    }

    /**
     * 调查录入 以AccidentReport为主表查询一对多关联查出reason表
     * @author admin
     * @date 2024-08-20 15:49:12
     * @param accidentReportDto accidentReportDto
     * @return List<AccidentReportDto>
     */
    @GetMapping("accidentReport/recordListAll")
    @ResponseBody
    @RequiresPermissions("accidentReport:view")
    public Map<String,Object> accidentReportRecordAll(AccidentReportDto accidentReportDto) {
        //如果不是总公司用户，或者模块管理员，则只查询自己上报的事故信息,或者指派的调查人是自己的事故
        if(!hasHeadCompanyRole() && !hasPermission(ModuleManagerPermissionConstant.ACCIDENT)){
            accidentReportDto.setCreatedBy(getCurrentUser().getUserId());
        }
//        accidentReportDto.setSurveyUserId(getCurrentUser().getUserId());
        if(null == accidentReportDto.getTenantId()){
            accidentReportDto.setTenantId(getCurrentTenantId());
        }
        return accidentReportService.findAccidentReportsAll(accidentReportDto);
    }

    /**
     * 整改查询（分页）
     * @author admin
     * @date 2024-08-07 16:43:01
     */
    @GetMapping("accidentReport/rectifyList")
    @ResponseBody
    @RequiresPermissions("accidentReport:view")
    public FebsResponse rectifyList(QueryRequest request, AccidentReportDto accidentReport) {
        accidentReport.setUserId(getCurrentUser().getUserId());
        if(null == accidentReport.getTenantId()){
            accidentReport.setTenantId(getCurrentTenantId());
        }
        Map<String, Object> dataTable = getDataTable(this.accidentReportService.rectifyList(request, accidentReport));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 AccidentReport
     * @author admin
     * @date 2024-08-07 16:43:01
     */
    @Log("新增AccidentReport")
    @PostMapping("accidentReport")
    @ResponseBody
    @RequiresPermissions("accidentReport:add")
    public FebsResponse addAccidentReport(@RequestBody AccidentReportDto accidentReportDto) throws FebsException {
        try {
            //必填校验
            checkNecessaryColumns(accidentReportDto,false);
            if(null == accidentReportDto.getTenantId()){
                accidentReportDto.setTenantId(getCurrentTenantId());
            }
            AccidentReport accidentReport = BeanHelper.copyProperties(accidentReportDto, AccidentReport.class);
            accidentReport.setCreatedBy(getCurrentUserId());
            accidentReport.setAccidentNo(accidentReportService.createAccidentNo(accidentReportDto.getTenantId(),getCurrentUser().getDeptId()));
            this.accidentReportService.createAccidentReport(accidentReport);
            //保存上报附件
            if(CollectionUtils.isNotEmpty(accidentReportDto.getAccidentReportFileList())){
                accidentReportDto.setFileType("1");
                accidentReportDto.setReportId(accidentReport.getReportId());
                saveAccidentReportFile(accidentReportDto,accidentReportDto.getAccidentReportFileList());
            }
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增AccidentReport失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 逻辑删除 AccidentReport
     * @author admin
     * @date 2024-08-07 16:43:01
     */
    @Log("逻辑删除AccidentReport")
    @GetMapping("accidentReport/delete/{id}")
    @ResponseBody
    @RequiresPermissions("accidentReport:delete")
    public FebsResponse deleteAccidentReport(@PathVariable("id") String accidentReportIds) throws FebsException {
        try {
            AccidentReport accidentReport = new AccidentReport();
            accidentReport.setDeletedBy(getCurrentUser().getUserName());
            accidentReport.setDeletedTime(new Date());
            accidentReport.setDeletedFlg(FebsConstant.INVALID);
            this.accidentReportService.deleteAccidentReport(accidentReport,accidentReportIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除AccidentReport失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 重工上报 AccidentReport
     * @author admin
     * @date 2024-08-09 14:43:01
     */
    @Log("重工上报AccidentReport")
    @GetMapping("accidentReport/noticeChic/{id}")
    @ResponseBody
    @RequiresPermissions("accidentReport:noticeChic")
    public FebsResponse noticeChic(@PathVariable("id") String accidentReportIds) throws FebsException {
        try {
            AccidentReport accidentReport = new AccidentReport();
            accidentReport.setNoticeChic("1");
            accidentReport.setNoticeDate(new Date());
            this.accidentReportService.noticeChic(accidentReport,accidentReportIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "重工上报失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
    * 物理删除 AccidentReport
    * @author admin
    * @date 2024-08-07 16:43:01
    */
    @Log("物理删除AccidentReport")
    @GetMapping("accidentReport/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("accidentReport:delete")
    public FebsResponse physicallyDeleteAccidentReport(@PathVariable("id") String accidentReportIds) throws FebsException {
        try {
            this.accidentReportService.physicallyDeleteAccidentReport(accidentReportIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除AccidentReport失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 修改 AccidentReport
     * @author admin
     * @date 2024-08-07 16:43:01
     */
    @Log("修改AccidentReport")
    @PostMapping("accidentReport/update")
    @ResponseBody
    @RequiresPermissions("accidentReport:edit")
    public FebsResponse updateAccidentReport(@Valid @RequestBody AccidentReportDto accidentReportDto) throws FebsException {
        try {
            //必填校验
            checkNecessaryColumns(accidentReportDto,true);
            accidentReportDto.setUpdatedBy(getCurrentUserId());
            accidentReportDto.setUpdatedTime(new Date());
            this.accidentReportService.updateAccidentReport(accidentReportDto);
            //保存上报附件
            if(CollectionUtils.isNotEmpty(accidentReportDto.getAccidentReportFileList())){
                accidentReportDto.setFileType("1");
                saveAccidentReportFile(accidentReportDto,accidentReportDto.getAccidentReportFileList());
            }
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改AccidentReport失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 调查录入 AccidentReport
     * @author admin
     * @date 2024-08-13 9:22:01
     */
    @Log("调查录入AccidentReport")
    @PostMapping("accidentReport/surveyRecord")
    @ResponseBody
    @RequiresPermissions("accidentReport:surveyRecord")
    public FebsResponse surveyRecord(@RequestBody AccidentReportDto accidentReportDto) throws FebsException {
        try {
            accidentReportDto.setUpdatedBy(getCurrentUser().getUserName());
            this.accidentReportService.updateAccidentReport(accidentReportDto);
            //保存事故伤亡人员表accident_report_inkury_user
            saveAccidentReportInkuryUser(accidentReportDto);
            //保存事故上报肇事人员表accident_report_culprit_user
            saveAccidentReportCulpritUser(accidentReportDto);
            //保存事故图解
            if(CollectionUtils.isNotEmpty(accidentReportDto.getReportImgFileList())){
                accidentReportDto.setFileType("2");
                saveAccidentReportFile(accidentReportDto,accidentReportDto.getReportImgFileList());
            }
            //保存事故分析图
            if(CollectionUtils.isNotEmpty(accidentReportDto.getReportAnalysisFileList())){
                accidentReportDto.setFileType("3");
                saveAccidentReportFile(accidentReportDto,accidentReportDto.getReportAnalysisFileList());
            }
            //保存事故调查文件
            if(CollectionUtils.isNotEmpty(accidentReportDto.getAccidentSurveyFileList())){
                accidentReportDto.setFileType("4");
                saveAccidentReportFile(accidentReportDto,accidentReportDto.getAccidentSurveyFileList());
            }
            //保存事故时间线accident_report_timeline
            if(CollectionUtils.isNotEmpty(accidentReportDto.getTimelineList())){
                saveAccidentReportTimeline(accidentReportDto,accidentReportDto.getTimelineList());
            }
            //保存事故整改accident_report_rectification
            if(CollectionUtils.isNotEmpty(accidentReportDto.getRectificationOpinionList())){
                saveAccidentReportRectification(accidentReportDto.getRectificationOpinionList());
            }
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "调查录入失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 调查录入提交审核 AccidentReport
     * @author admin
     * @date 2024-08-13 9:22:01
     */
    @Log("调查录入提交审核AccidentReport")
    @PostMapping("accidentReport/surveyRecordSubmit")
    @ResponseBody
    @RequiresPermissions("accidentReport:surveyRecord")
    public FebsResponse surveyRecordSubmit(@RequestBody AccidentReportDto accidentReportDto) throws FebsException {
        try {
            //校验事故报告下是否存在还未完成整改的事故原因 accident_report_reason ->rectification_status 整改状态不是5的
            AccidentReportReason accidentReportReason = new AccidentReportReason();
            accidentReportReason.setReportId(accidentReportDto.getReportId());
            List<AccidentReportReason> accidentReportReasonList = accidentReportReasonService.findAccidentReportReasonList(accidentReportReason);
            if(CollectionUtils.isNotEmpty(accidentReportReasonList)){
                long count = accidentReportReasonList.stream().filter(d -> !"5".equals(d.getRectificationStatus())).count();
                if (count>0) {
                    return new FebsResponse().fail().message("当前报告下存在未整改完成的事故原因，无法提交！");
                }else{
                    //修改事故报告的调查状态accident_report ->survey_status=4(调查待审核)
                    accidentReportDto.setSurveyStatus("4");
                    accidentReportService.updateById(accidentReportDto);
                }
            }
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "调查提交审核失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 整改录入 AccidentReport
     * @author admin
     * @date 2024-08-13 9:22:01
     */
    @Log("整改录入AccidentReportDto")
    @PostMapping("accidentReport/rectifyRecord")
    @ResponseBody
    @RequiresPermissions("accidentReport:rectifyRecord")
    public FebsResponse rectifyRecord(@RequestBody AccidentReportRectificationDto accidentReportRectificationDto) throws FebsException {
        try {
            this.accidentReportRectificationService.updateAccidentReportRectification(accidentReportRectificationDto);
            //保存事故整改附件 accident_report_reason_file
            if(CollectionUtils.isNotEmpty(accidentReportRectificationDto.getAccidentReportRectificationFileList())){
                saveAccidentReportRectificationFile(accidentReportRectificationDto,accidentReportRectificationDto.getAccidentReportRectificationFileList());
            }
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "整改录入失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 调查审核 AccidentReport
     * @author admin
     * @date 2024-08-13 9:22:01
     */
    @Log("调查审核AccidentReportDto")
    @PostMapping("accidentReport/surveyAudit")
    @ResponseBody
    @RequiresPermissions("accidentReport:surveyAudit")
    public FebsResponse surveyAudit(@RequestBody AccidentReportDto accidentReportDto) throws FebsException {
        try {
            User user = getCurrentUser();
            accidentReportDto.setSurveyAuditUserId(user.getUserId());
            accidentReportDto.setSurveyAuditRealName(user.getUname());
            accidentReportDto.setSurveyAuditDate(new Date());
            this.accidentReportService.updateAccidentReport(accidentReportDto);
            //保存上报调查审核记录 accident_survey_audit_record
            saveAccidentSurveyAuditRecord(accidentReportDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "调查审核失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 整改审核 AccidentReport
     * @author admin
     * @date 2024-08-13 9:22:01
     */
    @Log("整改审核AccidentReportDto")
    @PostMapping("accidentReport/rectifyAudit")
    @ResponseBody
    @RequiresPermissions("accidentReport:rectifyAudit")
    public FebsResponse rectifyAudit(@RequestBody AccidentReportReasonDto accidentReportReasonDto) throws FebsException {
        try {
            User user = getCurrentUser();
            accidentReportReasonDto.setRectificationAuditDate(new Date());
            accidentReportReasonDto.setRectificationAuditUserId(user.getUserId());
            accidentReportReasonDto.setRectificationAuditRealName(user.getUname());
            accidentReportReasonService.updateAccidentReportReason(accidentReportReasonDto);
            //是否转发警示教训
            if(StringUtils.isNotEmpty(accidentReportReasonDto.getCautionaryFlg()) && "1".equals(accidentReportReasonDto.getCautionaryFlg())){
                AccidentReport accidentReport = accidentReportService.getById(accidentReportReasonDto.getReportId());
//                baseCautionaryLessonService.saveCautionaryLessonFromOthers(accidentReport.getTenantId(),"1",accidentReport.getReportId(),accidentReport.getAccidentTitle(),accidentReport.getLeaderDeptId(),accidentReport.getLeaderDeptName(),getCurrentUserId());
            }
            //保存整改审核记录 accident_rectification_audit_record
            saveAccidentRectificationAuditRecord(accidentReportReasonDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "整改审核失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 保存整改审核记录 accident_rectification_audit_record
     * @author admin
     * @date 2024-08-28 16:43:01
     */
    private void saveAccidentRectificationAuditRecord(AccidentReportReasonDto accidentReportReasonDto){
        User user = getCurrentUser();
        AccidentRectificationAuditRecord accidentRectificationAuditRecord = new AccidentRectificationAuditRecord();
        accidentRectificationAuditRecord.setAuditResult(accidentReportReasonDto.getAuditResult());
        accidentRectificationAuditRecord.setAuditTime(new Date());
        accidentRectificationAuditRecord.setAuditReason(accidentReportReasonDto.getAuditReason());
        accidentRectificationAuditRecord.setTenantId(accidentReportReasonDto.getTenantId());
        accidentRectificationAuditRecord.setAuditUserId(user.getUserId());
        accidentRectificationAuditRecord.setCreatedBy(user.getUserId());
        accidentRectificationAuditRecord.setAuditRealName(user.getUname());
        accidentRectificationAuditRecord.setReportId(accidentReportReasonDto.getReportId());
        accidentRectificationAuditRecord.setReportReasonId(accidentReportReasonDto.getReportReasonId());
        accidentRectificationAuditRecordService.createAccidentRectificationAuditRecord(accidentRectificationAuditRecord);
    }

    /**
     * 保存事故上报调查审核记录 accident_survey_audit_record
     * @author admin
     * @date 2024-08-28 16:43:01
     */
    private void saveAccidentSurveyAuditRecord(AccidentReportDto accidentReportDto){
        User user = getCurrentUser();
        AccidentSurveyAuditRecord accidentSurveyAuditRecord = new AccidentSurveyAuditRecord();
        accidentSurveyAuditRecord.setAuditResult(accidentReportDto.getAuditResult());
        accidentSurveyAuditRecord.setAuditTime(new Date());
        accidentSurveyAuditRecord.setAuditReason(accidentReportDto.getAuditReason());
        accidentSurveyAuditRecord.setTenantId(accidentReportDto.getTenantId());
        accidentSurveyAuditRecord.setAuditUserId(user.getUserId());
        accidentSurveyAuditRecord.setCreatedBy(user.getUserId());
        accidentSurveyAuditRecord.setAuditRealName(user.getUname());
        accidentSurveyAuditRecord.setReportId(accidentReportDto.getReportId());
        accidentSurveyAuditRecordService.createAccidentSurveyAuditRecord(accidentSurveyAuditRecord);
    }

    /**
     * 调查指派 AccidentReport
     * @author admin
     * @date 2024-08-07 16:43:01
     */
    @Log("调查指派AccidentReport")
    @PostMapping("accidentReport/surveyAssign")
    @ResponseBody
    @RequiresPermissions("accidentReport:surveyAssign")
    public FebsResponse surveyAssign(@RequestBody AccidentReportDto accidentReportDto) throws FebsException {
        if(CollectionUtils.isEmpty(accidentReportDto.getTeamList())) {
            throw new FebsException("调查组不能为空");
        }
        try {
            accidentReportDto.setStatus(AccidentConstant.ACCIDENT_REPORT_PENDING);
            accidentReportDto.setSurveyStatus(AccidentConstant.ACCIDENT_ALLOCATED_FOR_SURVEY);
            accidentReportDto.setUpdatedBy(getCurrentUser().getUserName());
            this.accidentReportService.updateAndInsertTeam(accidentReportDto);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改AccidentReport失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 整改指派 AccidentReport
     * @author admin
     * @date 2024-08-07 16:43:01
     */
    @Log("整改指派AccidentReport")
    @PostMapping("accidentReport/rectificationAssign")
    @ResponseBody
    @RequiresPermissions("accidentReport:rectificationAssign")
    public FebsResponse rectificationAssign(@RequestBody AccidentReport accidentReport) throws FebsException {
        try {
            accidentReport.setStatus(AccidentConstant.ACCIDENT_REPORT_PENDING);
//            accidentReport.setRectificationStatus(AccidentConstant.ACCIDENT_ALLOCATED_FOR_RECTIFY);
            accidentReport.setUpdatedBy(getCurrentUser().getUserName());
            this.accidentReportService.updateById(accidentReport);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改AccidentReport失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    /**
     * 导出 AccidentReport的excel
     * @author admin
     * @date 2024-08-07 16:43:01
     */
    @PostMapping("accidentReport/excel")
    @ResponseBody
    @RequiresPermissions("accidentReport:view")
    public void export(QueryRequest queryRequest, AccidentReportDto accidentReport, HttpServletResponse response) throws FebsException {
        try {
            List<AccidentReportDto> accidentReports = this.accidentReportService.findAccidentReports(queryRequest, accidentReport).getRecords();
            ExcelKit.$Export(AccidentReport.class, response).downXlsx(accidentReports, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    private void setModelAttribute(Model model){
        model.addAttribute("currentUser",getCurrentUser());
        model.addAttribute("tenantList", getTenantList());
        model.addAttribute("tenantId", getCurrentTenantId());
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("accidentTypeList", dictService.findDictByCode("SAFETY_ACCIDENT_TYPE"));
        model.addAttribute("accidentLevelList", dictService.findDictByCode("SAFETY_ACCIDENT_LEVEL"));
        model.addAttribute("jobOperationList", dictService.findDictByCode("SAFETY_JOB_OPERATION"));
        model.addAttribute("injuryLevelList", dictService.findDictByCode("SAFETY_ACCIDENT_INJURY_LEVEL"));
        model.addAttribute("reasonTypeList", dictService.findDictByCode("SAFETY_ACCIDENT_REASON"));
        //部门
        List<Dept> deptList = deptService.list(new LambdaQueryWrapper<Dept>()
                                            .eq(Dept::getTenantId,getCurrentTenantId())
                                            .eq(Dept::getDeletedFlg,FebsConstant.VALID));
        model.addAttribute("deptList",deptList);
    }

    /**
     * 保存事故伤亡人员表 accident_report_inkury_user
     * @author admin
     * @date 2024-07-29 14:19:15
     * @param accidentReportDto accidentReportDto
     */
    private void saveAccidentReportInkuryUser(AccidentReportDto accidentReportDto){
        //先删除
        accidentReportInkuryUserService.deleteByReportIds(accidentReportDto.getReportId());
        if(CollectionUtils.isNotEmpty(accidentReportDto.getInjuryUserDataList())){
            List<AccidentReportInkuryUser> accidentReportUserList = accidentReportDto.getInjuryUserDataList().stream()
                    .map(d -> {
                        AccidentReportInkuryUser accidentReportInkuryUser = BeanHelper.copyProperties(d,AccidentReportInkuryUser.class);
                        accidentReportInkuryUser.setReportId(accidentReportDto.getReportId());
                        accidentReportInkuryUser.setCreatedTime(new Date());
                        accidentReportInkuryUser.setCreatedBy(getCurrentUser().getUserId());
                        return accidentReportInkuryUser;
                    }).collect(Collectors.toList());
            accidentReportInkuryUserService.saveBatch(accidentReportUserList);
        }
    }

    /**
     * 保存事故上报肇事人员 accident_report_culprit_user
     * @author admin
     * @date 2024-07-29 14:19:15
     * @param accidentReportDto accidentReportDto
     */
    private void saveAccidentReportCulpritUser(AccidentReportDto accidentReportDto){
        //先删除
        accidentReportCulpritUserService.deleteByReportIds(accidentReportDto.getReportId());
        if(CollectionUtils.isNotEmpty(accidentReportDto.getInjuryUserDataList())){
            List<AccidentReportCulpritUser> accidentReportUserList = accidentReportDto.getCulpritUserDataList().stream()
                    .map(d -> {
                        AccidentReportCulpritUser accidentReportCulpritUser = BeanHelper.copyProperties(d,AccidentReportCulpritUser.class);
                        accidentReportCulpritUser.setReportId(accidentReportDto.getReportId());
                        accidentReportCulpritUser.setCreatedTime(new Date());
                        accidentReportCulpritUser.setCreatedBy(getCurrentUser().getUserId());
                        return accidentReportCulpritUser;
                    }).collect(Collectors.toList());
            accidentReportCulpritUserService.saveBatch(accidentReportUserList);
        }
    }

    /**
     * 保存事故附件
     * @author admin
     * @date 2024-07-29 14:19:15
     * @param accidentReportDto accidentReportDto
     */
    private void saveAccidentReportFile(AccidentReportDto accidentReportDto,List<AccidentReportFile> fileList){
        //先删除，再保存
        accidentReportFileService.deleteByReportIds(accidentReportDto.getReportId(),accidentReportDto.getFileType());
        if(CollectionUtils.isNotEmpty(fileList)){
            List<AccidentReportFile> accidentReportFileList = fileList.stream()
                    .map(d -> {
                        AccidentReportFile accidentReportFile = BeanHelper.copyProperties(d,AccidentReportFile.class);
                        accidentReportFile.setReportId(accidentReportDto.getReportId());
                        accidentReportFile.setTenantId(accidentReportDto.getTenantId());
                        accidentReportFile.setReportFileType(accidentReportDto.getFileType());
                        accidentReportFile.setCreatedTime(new Date());
                        accidentReportFile.setCreatedBy(getCurrentUser().getUserId());
                        return accidentReportFile;
                    }).collect(Collectors.toList());
            accidentReportFileService.saveBatch(accidentReportFileList);
        }
    }

    /**
     * 保存事故原因附件 accident_report_rectification_file
     * @author admin
     * @date 2024-07-29 14:19:15
     * @param accidentReportRectificationDto accidentReportRectificationDto
     */
    private void saveAccidentReportRectificationFile(AccidentReportRectificationDto accidentReportRectificationDto,List<AccidentReportRectificationFile> fileList){
        //先删除，再保存
//        accidentReportReasonFileService.deleteByReportReasonIds(accidentReportRectificationDto.getReportReasonId(),accidentReportReasonDto.getReasonFileType());

        accidentReportRectificationFileService.deleteByReportRectificationId(accidentReportRectificationDto.getReportRectificationId());
        if(CollectionUtils.isNotEmpty(fileList)){
            List<AccidentReportRectificationFile> accidentReportRectificationFileList = fileList.stream()
                    .map(d -> {
                        AccidentReportRectificationFile accidentReportRectificationFile = BeanHelper.copyProperties(d,AccidentReportRectificationFile.class);
                        accidentReportRectificationFile.setReportId(accidentReportRectificationDto.getReportId());
                        accidentReportRectificationFile.setTenantId(accidentReportRectificationDto.getTenantId());
                        accidentReportRectificationFile.setReportRectificationId(accidentReportRectificationDto.getReportRectificationId());
                        accidentReportRectificationFile.setCreatedTime(new Date());
                        accidentReportRectificationFile.setCreatedBy(getCurrentUser().getUserId());
                        return accidentReportRectificationFile;
                    }).collect(Collectors.toList());
            accidentReportRectificationFileService.saveBatch(accidentReportRectificationFileList);
        }
    }

    /**
     * 保存事故时间线 accident_report_timeline
     * @author admin
     * @date 2024-07-29 14:19:15
     * @param accidentReportDto accidentReportDto
     * @param list list
     */
    private void saveAccidentReportTimeline(AccidentReportDto accidentReportDto,List<AccidentReportTimeline> list){
        //先删除，再保存
        accidentReportTimelineService.deleteByReportIds(accidentReportDto.getReportId());
        if(CollectionUtils.isNotEmpty(list)){
            List<AccidentReportTimeline> accidentReportTimelineList = list.stream()
                    .map(d -> {
                        AccidentReportTimeline accidentReportTimeline = BeanHelper.copyProperties(d,AccidentReportTimeline.class);
                        accidentReportTimeline.setReportId(accidentReportDto.getReportId());
                        accidentReportTimeline.setTenantId(accidentReportDto.getTenantId());
                        accidentReportTimeline.setCreatedTime(new Date());
                        accidentReportTimeline.setCreatedBy(getCurrentUser().getUserId());
                        return accidentReportTimeline;
                    }).collect(Collectors.toList());
            accidentReportTimelineService.saveBatch(accidentReportTimelineList);
        }
    }

    /**
     * 保存事故整改 list
     * @author admin
     * @date 2024-07-29 14:19:15
     * @param list list
     */
    private void saveAccidentReportRectification(List<AccidentReportRectification> list){
        if(CollectionUtils.isNotEmpty(list)){
            list.forEach(d -> {
                //id为空则新增
                if(StringUtils.isEmpty(d.getReportRectificationId())){
                    AccidentReportRectification rectification = BeanHelper.copyProperties(d,AccidentReportRectification.class);
                    rectification.setCreatedTime(new Date());
                    rectification.setCreatedBy(getCurrentUser().getUserId());
                    accidentReportRectificationService.createAccidentReportRectification(rectification);
                }else{
                    //更新操作
                    accidentReportRectificationService.updateById(d);
                }
            });
        }
    }

    /**
     * 保存事故原因 list
     * @author admin
     * @date 2024-07-29 14:19:15
     * @param accidentReportDto accidentReportDto
     * @param list list
     */
//    private void saveAccidentReportRectification(AccidentReportDto accidentReportDto,List<AccidentReportReasonDto> list){
//        if(CollectionUtils.isNotEmpty(list)){
//            list.forEach(d -> {
//                //id为空则新增
//                if(StringUtils.isEmpty(d.getReportReasonId())){
//                    AccidentReportReason accidentReportReason = BeanHelper.copyProperties(d,AccidentReportReason.class);
//                    accidentReportReason.setCreatedTime(new Date());
//                    accidentReportReason.setSurveyDate(new Date());
//                    accidentReportReason.setCreatedBy(getCurrentUser().getUserId());
//                    accidentReportReasonService.createAccidentReportReason(accidentReportReason);
//                    //再保存事故调查与原因附件
//                    if(CollectionUtils.isNotEmpty(d.getAccidentReasonSurveyFileList())){
//                        d.setReasonFileType("1");
//                        d.setReportReasonId(accidentReportReason.getReportReasonId());
//                        saveAccidentReportReasonFile(d,d.getAccidentReasonSurveyFileList());
//                    }
//                }else{
//                    //更新操作
//                    accidentReportReasonService.updateById(d);
//                    d.setReasonFileType("1");
//                    saveAccidentReportReasonFile(d,d.getAccidentReasonSurveyFileList());
//                }
//            });
//        }
//    }

    /**
     * 新增/编辑保存时，字段必填项校验
     * @author dinghaitao
     * @date 2024-08-30 17:06:50
     */
    public void checkNecessaryColumns(AccidentReportDto accidentReportDto,boolean editFlg) throws FebsException {
        if(editFlg && StringUtils.isEmpty(accidentReportDto.getReportId())){
            throw new FebsException("主键不能为空");
        } else if(StringUtils.isEmpty(accidentReportDto.getAccidentTitle())){
            throw new FebsException("事故标题不能为空");
        } else if(StringUtils.isEmpty(accidentReportDto.getAccidentType())){
            throw new FebsException("请选择事故类型");
        } else if(StringUtils.isEmpty(accidentReportDto.getAccidentLevel())){
            throw new FebsException("请选择事故等级");
        } else if(null == accidentReportDto.getAccidentDate()){
            throw new FebsException("请选择事故发生时间");
        } else if(StringUtils.isEmpty(accidentReportDto.getAccidentPlace())){
            throw new FebsException("事故发生地点不能为空");
        } else if(StringUtils.isEmpty(accidentReportDto.getPreliminarilyDamage())){
            throw new FebsException("初步损失情况不能为空");
        } else if(StringUtils.isEmpty(accidentReportDto.getPreliminarilyDescript())){
            throw new FebsException("初步描述不能为空");
        }
    }



}
